import xlwt
import xlrd
import os
import logging.config
import traceback


excl_base_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "excl_files")
print(excl_base_path)

class read_excl():
    def __init__(self, file_name, read_type):
        '''
        :param file_name: excl 名字
        :param read_type: 获取excl的方式  index/name
        '''
        self.excl_name = file_name
        self.type = read_type
        self.INIT_EXCL()

    def INIT_EXCL(self):
        '''
        初始化excl
        :return:
        '''
        try:
            self.excl = xlrd.open_workbook(r""+os.path.join(excl_base_path, self.excl_name))
            if type(self.type) == int:
                self.sheet = self.excl.sheet_by_index(self.type)
            elif type(self.type) == str:
                self.sheet = self.excl.sheet_by_name(self.type)
            else:
                logging.info("不知道怎么构造sheet对象")
        except Exception as f:
            print(f)


    def read_return_list_dict(self):
        '''
        读取excl文件中的内容
        返回list或者字典格式
        :return:
        '''
        try:
            self.rows = self.sheet.nrows
            self.cols = self.sheet.ncols
            return self._read_excl()
        except Exception as f:
            print(f)


    def _read_excl(self):
        '''
        读取excl文件数据
        只处理str 类型的文件
        :return:
        '''
        if hasattr(self, "sheet"):
            excl_list = []
            for index in range(1,self.rows):
                col_list = []
                for col in range(self.cols):
                    try:
                        if self.sheet.cell_value(index,3):
                            ret = self.sheet.cell_value(index,col)
                            col_list.append(ret)
                        else:
                            continue
                    except Exception:
                        logging.error(traceback.format_exc())
                        logging.info("获取单元格数据失败")
                # 空行处理
                excl_list.append(col_list)
            return excl_list
        else:
            logging.info("没有self.sheet对象")
            return "啥都没有"

